package com.fastjrun.share.demo.service.impl;

import com.fastjrun.common.ServiceException;
import com.fastjrun.share.demo.common.CodeMsgConstants;
import com.fastjrun.share.demo.dao.SysUserDao;
import com.fastjrun.share.demo.dto.ModifyPwdDTO;
import com.fastjrun.share.demo.entity.SysUser;
import com.fastjrun.share.demo.service.BaseDemoService;
import com.fastjrun.share.demo.service.SecurityService;
import com.fastjrun.share.demo.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


/**
 * 注意：本内容仅限于公司内部传阅，禁止外泄以及用于其他的商业目的
 *
 * @author cuiyingfeng
 * @Copyright 2021 快嘉. All rights reserved.
 */
@Service("securityService")
public class SecurityServiceImpl extends BaseDemoService
        implements SecurityService {
    @Autowired
    SysUserDao sysUserDao;

    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * 修改密码
     */
    public void password(ModifyPwdDTO requestBody) {
        String oldPassword = requestBody.getOldPassword();
        String newPassword = requestBody.getNewPassword();
        String repPassword = requestBody.getRepPassword();
        if (!newPassword.equals(repPassword)) {
            throw new ServiceException(CodeMsgConstants.SECURITYSERVICEIMPL_21001, this.serviceMessageSource.getMessage(CodeMsgConstants.SECURITYSERVICEIMPL_21001, null, null));
        }
        SysUser sysUser = this.getCurrentUser();

        if (!passwordEncoder.matches(oldPassword, sysUser.getPassword())) {
            throw new ServiceException(CodeMsgConstants.SECURITYSERVICEIMPL_21002, this.serviceMessageSource.getMessage(CodeMsgConstants.SECURITYSERVICEIMPL_21002, null, null));
        }
        sysUserDao.modifyPassword(sysUser.getId(), passwordEncoder.encode(newPassword));

    }


    /**
     * 获取用户信息
     */
    @Override
    public UserInfoVO userinfo() {
        UserInfoVO userInfoVO0 = new UserInfoVO();
        SysUser sysUser = this.getCurrentUser();
        userInfoVO0.setName(sysUser.getUsername());
        return userInfoVO0;
    }
}
